$(document).ready( function(){
	$("body").on("click", ".toCart", function(){
		
		$("#ajaxLoader").show();
		
		var productID = $(this).attr("product_id");
		
		$("#cartModal .modalCart").attr("product_id", productID);
		
		var dataString = "&get_property_list=1&product_id="+productID;
		
		$.ajax({
			type:'POST',
			url: scriptsURL+"libs/ajax/ajax-includes.php",
			data: dataString,
			}).done(function(response){
				if(response && response != "")
				{
					$("#cartModal .productDetails").html(response);
					
					$("#cartModal").modal({
						 keyboard: false,
						 backdrop: "static"
					});
				}
				$("#ajaxLoader").hide();
		});
		
		return false;
	});
	
	$(".productDetails").on("click", "a.property", function(){
		
		var filterHolder = $(this).parents(".filterList.holder");
		
		var newPropertyID = $(this).parents("li.properties").attr("property_id");
		var newPropertyValueID = $(this).attr("property_value_id");
		
		getFilterList(filterHolder, newPropertyID, newPropertyValueID);
		
		return false;
	});
	
	$(".productDetails").on("click", ".removeFilters", function(){
		newPropertyID = undefined;
		newPropertyValueID = undefined;
		var filterHolder = $(this).siblings(".filterList.holder");
		getFilterList(filterHolder);
		$(this).addClass("hidden");
	});
	
	$("#addToCart").on("click", function(){
		if($(this).hasClass("modalCart"))
		{
			var filterHolder = $("#cartModal .productDetails").find(".filterList.holder");
			var quantity = $("#cartModal .productDetails").find("input[name=quantity]").val();
		}
		else
		{
			var filterHolder = $(this).parents(".productDetails").find(".filterList.holder");
			var quantity = $(this).parents(".buttons").find("input[name=quantity]").val();
		}
		
		var propertyList = getPropertyList(filterHolder);
		var productID = $(this).attr("product_id");
		
		
		addToCart(productID, quantity, filterHolder, propertyList);
		
		return false;
	});
	
	$(".productDetails").on("change", "input[name=quantity]", function(){
		if($(this).val() && $(this).val() > 0)
		{
			$(this).parent().removeClass("has-error");
			$(this).siblings(".error").html("").addClass("hidden");
		}
	});
	
	$(".quantityInput").on("focus",function(){
		$(this).siblings("button").fadeIn();
	});
	
	$(".changeQuantity").on("click", function(){
		var quantityInput = $(this).siblings(".quantityInput");
		
		var initialValue = quantityInput.attr("initial_value");
		var quantity = quantityInput.val();
		if(initialValue == quantity)
		{
			$(this).fadeOut();
		}
		else
		{
			var productID = quantityInput.attr("product_id");
			var stockID = quantityInput.attr("stock_id");
			$("#ajaxLoader").show();
			var dataString = "&change_quantity=1&product_id="+productID+"&stock_id="+stockID+"&quantity="+quantity;
			
			$.ajax({
				type:'POST',
				url: scriptsURL+"libs/ajax/ajax-includes.php",
				data: dataString,
				}).done(function(responseJSON)
				{
					response = JSON.parse(responseJSON);
					
					handleCartResponse(response, quantityInput);
					
					$("#ajaxLoader").hide();
				});
			}
		
		return false;
	});
	
	$(".quantityInput").on("blur", function(){
		var initialValue = $(this).attr("initial_value");
		var quantity = $(this).val();
		
		if(initialValue == quantity)
		{
			$(this).siblings(".changeQuantity").fadeOut();
		}
	});
	
	$(".removeFromCart").on("click", function(){
		$("#ajaxLoader").show();
		var productID = $(this).attr("product_id");
		var stockID = $(this).attr("stock_id");
		
		var dataString = "&remove_from_cart=1&product_id="+productID+"&stock_id="+stockID;
		
		$.ajax({
		type:'POST',
		url: scriptsURL+"libs/ajax/ajax-includes.php",
		data: dataString,
		}).done(function(responseJSON)
		{
			response = JSON.parse(responseJSON);
			
			handleCartResponse(response);
			
			$("#ajaxLoader").hide();
		});
	});
	
	$("#sendCoupon").on("click", function(){
		$("#ajaxLoader").show();
		
		var couponCode = $("#coupon_code").val();
		var dataString = "&add_coupon="+couponCode;
		
		$.ajax({
		type:'POST',
		url: scriptsURL+"libs/ajax/ajax-includes.php",
		data: dataString,
		}).done(function(responseJSON)
		{
			response = JSON.parse(responseJSON);
			
			if(response.error)
			{
				$("#messageDialog .modal-body").html("<div class='alert alert-danger'><span class='glyphicon glyphicon-ban-circle'></span> "+response.error+"</div>");
				if(response.link)
				{
					$("#messageDialog .modal-body").append(response.link);
				}
				$('#messageDialog').modal('show');
			}
			
			if(response.success)
			{
				$("#messageDialog .modal-body").html("<div class='alert alert-success'><span class='glyphicon glyphicon-ok-sign'></span> "+response.success+"</div>");
				$('#messageDialog').modal('show');
				
				$("#messageDialog").on("hide.bs.modal", function(){
					$("#ajaxLoader").show();
					location.reload();
				});
			}
			
			$("#ajaxLoader").hide();
		});
		
	});
	
	
});


function getFilterList(filterHolder, newPropertyID, newPropertyValueID)
{
	$("#ajaxLoader").show();
	
	var propertyList = [];
	if(newPropertyID && newPropertyValueID)
	{
		propertyList = getPropertyList(filterHolder);
		propertyList.push({"property_id" : newPropertyID, "property_value_id" : newPropertyValueID});
		filterHolder.parents(".productDetails").find(".removeFilters").removeClass("hidden");
		
	}
	
	var selectedValues = JSON.stringify(propertyList);
	var productID =  filterHolder.attr("product_id");
	
	dataString = "&get_filter_list=1&product_id="+productID+"&selected_values="+selectedValues;
	
	$.ajax({
		type:'POST',
		url: scriptsURL+"libs/ajax/ajax-includes.php",
		data: dataString,
		}).done(function(responseJSON)
		{
			response = JSON.parse(responseJSON);
			if(response.message && response.message != "")
			{
				$("#messageDialog .modal-body").html("<p>"+response.message+"</p>");
				$('#messageDialog').modal('show');
			}
			else
			{
				if(response.price)
				{
					filterHolder.parents(".productDetails").find(".productPrice").html(response.price);
				}
				
				if(response.stock_text)
				{
					if(response.quantity != undefined)
					{
						$("#addToCart").attr("quantity", response.quantity);
					
						if(response.quantity == 0)
						{
							useClass = "danger";
						}
						else if(response.quantity <= 5)
						{
							useClass = "warning";
						}
						else
						{
							useClass = "";
						}
						filterHolder.parents(".productDetails").find(".stockInfo").html(response.stock_text).removeClass("danger").removeClass("warning").removeClass("hidden").addClass(useClass);
						filterHolder.parents(".productDetails").find("input[name=quantity]").attr("max", response.quantity);
					}
				}
				else
				{
					
					filterHolder.parents(".productDetails").find(".stockInfo").addClass("hidden");
				}
				
				if(response.stock_id)
				{
					$("#addToCart").attr("stock_id", response.stock_id);
				}
				
				
				
				if(response.property_values)
				{
					filterHolder.find("a.property").each( function(){
						var currentValueId = $(this).attr("property_value_id");
						var currentID = $(this).parents(".properties").attr("property_id");
						if (response.property_values[currentValueId] == currentID)
						{
							$(this).fadeIn().addClass("visible");
						}
						else
						{
							$(this).fadeOut().removeClass("visible");
						}
					});
					
					filterHolder.find("li.properties").each( function(){
						if($(this).children("a.property.visible").length == 1)
						{
							$(this).children("a.property.visible").addClass("selected");
							$(this).siblings(".error").addClass("hidden");
						}
						else
						{
							$(this).children("a.property.visible").removeClass("selected");
							$(this).siblings(".error").removeClass("hidden");
						}
					});
				}
				else
				{
					filterHolder.find("a.property.selected").removeClass("selected");
				}
			}
			$("#ajaxLoader").hide();
	});
}

function getPropertyList(filterHolder)
{	
	propertyList = [];
	
	filterHolder.find("li.properties").each( function()
	{
		if($(this).children("a.selected").length > 0)
		{
			var propertyID = $(this).attr("property_id");
			var selectedValue = $(this).children("a.selected").attr("property_value_id");
			propertyList.push({"property_id" : propertyID, "property_value_id" : selectedValue});
		}
		
		
	});
	
	return propertyList;
}

function addToCart(productID, quantity, filterHolder, propertyList)
{
	$("#ajaxLoader").show();
	
	propertyList = JSON.stringify(propertyList);
	
	var dataString = "&add_to_cart=1&product_id="+productID+"&quantity="+quantity+"&selected_values="+propertyList;
	$.ajax({
		type:'POST',
		url: scriptsURL+"libs/ajax/ajax-includes.php",
		data: dataString,
		}).done(function(responseJSON){
			
			response = JSON.parse(responseJSON);
			
			if(response.property_errors)
			{
				$.each(response.property_errors, function(index,message){
					filterHolder.find("li[property_id="+index+"]").siblings(".error").html(message).removeClass("hidden");
				});
			}
			
			if(response.quantity)
			{
				filterHolder.parents(".productDetails").find("input[name=quantity]").parent().addClass("has-error");
				filterHolder.parents(".productDetails").find("input[name=quantity]").parent().children(".error").html(response.quantity).removeClass("hidden");
			}
			
			if(response.error)
			{
				$("#messageDialog .modal-body").html("<div class='alert alert-danger'><span class='glyphicon glyphicon-ban-circle'></span> "+response.error+"</div>");
				$('#messageDialog').modal('show');
			}
			
			if(response.success)
			{
				$("#messageDialog .modal-body").html("<div class='alert alert-success'><span class='glyphicon glyphicon-ok-sign'></span> "+response.success+"</div>");
				$('#messageDialog').modal('show');
				
				$("#cartModal").modal("hide");
				
				refreshCart();
			}
			
			
			$("#ajaxLoader").hide();
		}
	);
}

function refreshCart()
{
	dataString = "&refresh_cart=1";
	
	$.ajax({
		type:'POST',
		url: scriptsURL+"libs/ajax/ajax-includes.php",
		data: dataString,
		}).done(function(response){
			$("#cartContainer").html(response);
	});
}

function goBack(){
	window.history.back();
}

function handleCartResponse(response, quantityInput)
{
	if(response.error)
	{
		$("#messageDialog .modal-body").html("<div class='alert alert-danger'><span class='glyphicon glyphicon-ban-circle'></span> "+response.error+"</div>");
		$('#messageDialog').modal('show');
	}
	
	if(response.success)
	{
		$("#messageDialog .modal-body").html("<div class='alert alert-success'><span class='glyphicon glyphicon-ok-sign'></span> "+response.success+"</div>");
		$('#messageDialog').modal('show');
		
		if(quantityInput)
		{
			quantity = quantityInput.val();
			
			if(response.new_vat && response.new_vat != "")
			{
				quantityInput.parents("td").siblings("td.vat").html(response.new_vat);
			}
			
			if(response.new_total && response.new_total != "")
			{
				quantityInput.parents("td").siblings("td.perTotal").html(response.new_total);
			}
			
			quantityInput.attr("initial_value", quantity);
			quantityInput.siblings(".changeQuantity").fadeOut();
		}
		
		if(response.new_per_total && response.new_per_total != "")
		{
			$("#perTotal").html(response.new_per_total);
		}
		
		if(response.new_grand_total && response.new_grand_total != "")
		{
			$("#grandTotal").html(response.new_grand_total);
		}
		
		if(response.transport_price && response.transport_price != "")
		{
			$("#transportPrice").html(response.transport_price);
		}
		
		refreshCart();
	}
	
	if(response.remove_row && response.remove_row > 0)
	{
		var tableBody = $("#cartTable").children("tbody");
		
		tableBody.children("#row_"+response.remove_row).remove();
		tableBody.children("tr.productRow").each( function(index, element){
			$(this).children("td:first").html(index+1);
		});
		
	}
}
